import requests
import json
from urllib import parse
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators import csrf
from django.http import JsonResponse
import sys
import mysql.connector
import sqlite3

from myapp.models import Update, User

versiondict={'A':'普通版','V':'代理版','J':'聚鑫头条','Y':'优阅日记'}
def get_sql(database,sql):
    conn = sqlite3.connect(database)
    cursor = conn.cursor()
    c = cursor.execute(sql).fetchall()
    return c

def index(request):
    list = []
    database='data.sqlite3'
    sql='select count(*) from course'
    list=get_sql(database,sql)
    context = {}
    context['listindex'] = list
    return render(request, 'data.html', context)

def topnews(request):
    context = {}
    user = request.session.get('user', 'False')
    if user != 'False':
        person=User.objects.filter(account=user)[0]
        database='db.sqlite3'
        sql='select count(*) from myapp_customer where author="{}"'.format(user)
        list=get_sql(database,sql)
        context['listindex'] = list
        context['testcard'] = person.testcard
        context['weekcard'] = person.weekcard
        context['monthcard'] = person.monthcard
        context['foevercard'] = person.foevercard
        list=[]
        for i in person.versionstring:
            templist={'string':i,'version':versiondict[i]}
            list.append(templist)
        context['versions'] = list
        return render(request, 'topnews.html', context)
    else:
        context['message'] = '请先登录！'
        context['user'] = '游客您好，'
        return render(request, 'welcome.html', context)

def sys(request):
    context = {}
    user = request.session.get('user', 'False')
    if user == 'liuxu':
        i=Update.objects.filter(type='latest')[0]
        context['version'] = i.version
        context['detial'] = i.detial
        context['force'] = i.force
        return render(request, 'admin.html', context)
    else:
        context['message'] = '请先登录！'
        context['user'] = '游客您好，'
        return render(request, 'welcome.html', context)
